<?php

namespace app\modules\Order\controllers;

use Yii;
use app\modules\Product\models\Product;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderRoom;
use app\modules\Order\models\OrderRoomSearch;
use app\modules\Order\models\OrderRoomCustomer;
use app\modules\Order\models\OrderRefund;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\Pagination;
use yii\filters\AccessControl;

/**
 * RoomController implements the CRUD actions for OrderRoom model.
 */
class RoomController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
				//	'delete' => ['post'],
				],
			],
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					[
						'allow' => true,
						'roles' => ['@'],
					],
				],
			],
		];
	}


	//  分配房号 
	public function actionList($product_id, $type=1){//{{{
		// 1 以舱房类型展示  2 以订单格式展示
		$product = Product::findOne($product_id);

		$data = OrderRoom::find()->where(['order_room.product_id'=>$product_id, 'order_room.status'=>1, 'order_room.stock'=>1]); 

		if($type == 1){
			$data->join('LEFT JOIN', 'order' , 'order.id=order_room.order_id');
			$data->orderBy('order.relation, room_id'); //code , 
			//$data->orderBy('order_id'); //code, 
			//$data->orderBy('room_id'); //code,
		}elseif($type == 2){
			
			$data->orderBy('room_id'); //code,
		}

		//$pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => 10]);
		//$model = $data->offset($pages->offset)->limit($pages->limit)->all();
		$model = $data->all(); 

		$all = [];

		if($type == 1){
			if($model){
			
				$all = \yii\helpers\ArrayHelper::map($model, 'id', function($model){ return $model;}, 'order_id');
			}
        	return $this->render('list', ['model'=>$model, 'all'=>$all, 'product'=>$product , 'type'=>$type] );
		}elseif($type == 2){
			
        	return $this->render('list2', ['model'=>$model, 'all'=>$all, 'product'=>$product , 'type'=>$type] );
		}


	}//}}}

	// 修改房号
	public function actionEditCode($id, $code){//{{{
		
        $model = $this->findModel($id);

		if(trim($code)){
			$ret = OrderRoom::find()->where(['product_id'=>$model->product_id, 'code'=>trim($code),'status'=>1])->one();
			if($ret){
				return json_encode(["output"=>false,"message"=>"该房号已经被分配"]);
			}
		}

		$model->code = trim($code);

		return $model->save();
	}//}}}

	public function actionEditFinal($id, $final_room_id){//{{{
		
        $model = $this->findModel($id);

		if(trim($final_room_id)){

			$model->final_room_id = $final_room_id;

			$model->save();

			$product = Product::findOne($model->product_id);
			$data = [];
			if($product->stock == 1){ // 国内航线
				// 获取所有房型
				$all = $product->productRoom;
				$data = \yii\helpers\ArrayHelper::map($all, 'id', function($model){ return $model->room->name . $model->room->code .'  ' . $model->people .'人';} );

			}elseif($product->stock == 2){ // 海外航线

				$t = json_decode($product->rooms, true);
				foreach($t as $key=>$val){
					$data[$key] = $val['name'];	
				}
			}

			print_r(json_encode(['output'=>$data[$model->final_room_id], 'message'=>"" ]));
		}
	}//}}}


	public function actionEditFinalNum($id, $final_num){//{{{
		
        $model = $this->findModel($id);

		if(trim($final_num)){

			$model->final_num = $final_num;

			$model->save();

			print_r(json_encode(['output'=>$model->final_num, 'message'=>"" ]));
		}
	}//}}}

    /**
     * Lists all OrderRoom models.
     * @return mixed
     */
    public function actionIndex($order_id){//{{{

        if(empty($order_id)){
            return false;
        }

        $searchModel = new OrderRoomSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    } //}}}

    /**
     * Displays a single OrderRoom model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new OrderRoom model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new OrderRoom();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing OrderRoom model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing OrderRoom model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

	//  订单下舱房取消
	public function actionRemove($id, $desc){//{{{

        $model = $this->findModel($id);  // model Room table
		// 判断是否关联了客户信息
        $ret = OrderRoomCustomer::find()->where( ['order_id'=>$model->order_id, 'order_room_id'=>$model->id] )->all();
		if($ret){
			echo "error1"; 	//echo "<script>alert('请先取消舱房填写的入住人');</script>";
			return false;
		}
		// 判断是否已加入分团	// 判断是否已分配房号
		// 判断是否拼房
		if($model->merge_id){ //todo 
			echo "error2";		
			return false;
		}

		if($model->delete()){
			// 记录退舱房申请记录
			$refund = new OrderRefund();
			$refund->product_id = $model->product_id;
			$refund->order_id = $model->order_id;
			$refund->order_room_id = $model->id;
			$refund->room_price = $model->price;  // 舱房的金额
			$refund->created_at = date("Y-m-d H:i:s");
			$refund->user_id    = Yii::$app->user->id;
			$refund->params =  json_encode($model->getAttributes());
			$refund->desc = $desc;

			$order = Order::findOne($refund->order_id);
			if($model->order->status == 1){ // 占位订单  直接记录状态为占位直接取消 , 无需审批
				$refund->status = 3;

				$refund->price = 0; //	$model->price;
				$refund->examine_id = 93; // 操作人 记录为系统
				$refund->check_at = date("Y-m-d H:i:s");
				
				$p = $refund->room_price - $refund->price;	// 总金额 - 扣除金额  = 退还金额
				$p = ($p >= 0) ? $p : 0;

				$order->refund_price = ($order->refund_price + $refund->price); // 累加以前的扣除金额

				$order->total_sale = $order->total_sale - $p;  //  计算舱房金额
				// 重新计算订单金额 
				//$total =  $order->price - $p;  // 实际金额  = 当前实际金额 - 退款金额  (舱房金额  - 已审批优惠  + 附加费)
				// 计算优惠金额	及 佣金金额  todo
        		$price = $order->total_sale - $order->sale_price - $order->commiss;

				// 计算附加费金额
				if($order->priceSum){
					$price = $price+$order->priceSum;
				}

        		$price = ($price <=0) ? 0 : $price;
        		$order->price = $price;
				
				//$order->price = ($total <0) ? 0 : $total;
				$ret = $order->save();
			}
			
			$ret = $refund->save();
			// 记录日志
			$name = $model->productRoom->room->name . '  ' . $model->productRoom->room->code ;
			Yii::$app->logs->info($order->id, 1, sprintf("取消舱房 %s", $name));

			// 变更订单状态
			Yii::$app->orderblock->order_status($order);
		}

		echo "true";
	}//}}}

	// 取消审批列表
	public function actionRefund(){//{{{

		if(!Yii::$app->user->can("sale_check")){
			return false;
		}
	
		$data = OrderRefund::find();

		$data->andWhere(['status'=>1]);
		$data->orderBy('status');
		//$pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => 10]);
		//$model = $data->offset($pages->offset)->limit($pages->limit)->all();

		$models = $data->all(); 

        return $this->render('refund', ['models' => $models]);
	}//}}}

	// 审批 取消的舱房
	public function actionCheck(){//{{{
		$params = Yii::$app->request->get();

		$id = $params['id'];
		$price = $params['price']; // 扣除金额
		// 判断金额是否合法 

		$refund = OrderRefund::findOne($id);
		if($refund->status == 1){
			$refund->price = $price;
			$refund->status = 2;
			$refund->examine_id = Yii::$app->user->id;
			$refund->check_at = date("Y-m-d H:i:s");
			
			if($refund->save()){
				$p = $refund->room_price - $refund->price;	// 总金额 - 扣除金额  = 退还金额
				$p = ($p >= 0) ? $p : 0;

				$order = Order::findOne($refund->order_id);
				$order->refund_price = ($order->refund_price + $refund->price); // 累加以前的扣除金额

				$order->total_sale = $order->total_sale - $p;  //  计算舱房金额

				// 计算优惠金额	及 佣金金额  todo
        		$price = $order->total_sale - $order->sale_price - $order->commiss;

				// 计算附加费金额
				if($order->priceSum){
					$price = $price+$order->priceSum;
				}

        		$price = ($price <=0) ? 0 : $price;
        		$order->price = $price;
				// ----------------------------
				//$p = $refund->room_price - $price;	// 总金额 - 扣除金额  = 退还金额
				//$p = ($p >= 0) ? $p : 0;

				//$order = Order::findOne($refund->order_id);
				//$order->refund_price = ($order->refund_price + $refund->price); // 累加以前的扣除金额

				//$order->total_sale = $order->total_sale - $p;  //  计算舱房金额
				//$total =  $order->price - $p;  // 实际金额  = 当前实际金额 - 退款金额  (舱房金额  - 已审批优惠  + 附加费)
				//$order->price = ($total <0) ? 0 : $total;
				$ret = $order->save();

				// 变更订单状态
				Yii::$app->orderblock->order_status($order);

				return $ret;
				//$total =  $order->total_sale - $order->sale_price + $order->priceSum;  //  舱房金额  - 优惠  + 附加费
			}
		}else{
		
			return json_encode(["output"=>false,"message"=>"已审批， 不可重复审批"]);
		}
	}//}}}

	// 修改 佣金 后返 金额
	public function actionCommissAjax(){//{{{
        $data = yii::$app->request->get(); 
		
		$r = true;
        if(isset($data['OrderRoom']['id'])){
            $model = $this->findModel($data['OrderRoom']['id']);
			$model->load($data);
			//  佣金计算	$ret = $model->save();
			
			$r = Yii::$app->orderblock->commiss($model);
		}
		if($r !== true){
			print_r(json_encode(['output'=>$r, 'message'=>"佣金金额无效, 佣金最大上线  ". $r ]));
		}else{
			print_r($r);
		}
	}//}}}


    /**
     * Finds the OrderRoom model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return OrderRoom the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = OrderRoom::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
